/*
 * DiffCallback.java
 * business
 *
 * Created by ChenTao on 2017/3/2.
 *
 * Copyright (c) 2017年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.ui.widget.recyclerview;

import android.support.annotation.Nullable;
import android.support.v7.util.DiffUtil;

import java.util.List;

/** 计算数据集的差异 */
public abstract class DiffCallback<T> extends DiffUtil.Callback {

    private List<T> mOldData;

    private List<T> mNewData;

    public DiffCallback(List<T> oldData, List<T> newData) {
        mOldData = oldData;
        mNewData = newData;
    }

    @Override
    public int getOldListSize() {
        return mOldData.size();
    }

    @Override
    public int getNewListSize() {
        return mNewData.size();
    }

    @Override
    public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
        T oldItem = mOldData.get(oldItemPosition);
        T newItem = mNewData.get(newItemPosition);
        return areItemsTheSame(oldItem, newItem);
    }

    @Override
    public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
        T oldItem = mOldData.get(oldItemPosition);
        T newItem = mNewData.get(newItemPosition);
        return areContentsTheSame(oldItem, newItem);
    }

    @Nullable
    @Override
    public Object getChangePayload(int oldItemPosition, int newItemPosition) {
        // 当areItemsTheSame 返回 true , 且 areContentsTheSame 返回 false时，调用
        // 通过此方法可以完成定向刷新
        T oldItem = mOldData.get(oldItemPosition);
        T newItem = mNewData.get(newItemPosition);
        return getChangePayload(oldItem, newItem);
    }

    public List<T> getNewData() {
        return mNewData;
    }

    /** 判断Item是否相同 */
    public abstract boolean areItemsTheSame(T oldItem, T newItem);

    /** 具体比较Item内容是否相同 */
    public abstract boolean areContentsTheSame(T oldItem, T newItem);

    /** 返回两个Item中不同的字段 */
    public abstract Object getChangePayload(T oldItem, T newItem);
}
